package com.log;

import com.alibaba.fastjson.JSONObject;
import com.util.UserInfo;
import com.util.UserUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(-100)
@Component
@Aspect
@Slf4j
public class LogAOP {

    private static final String JSON_KEY = "logjson";

    @Pointcut("@annotation(com.log.Log)")
    public void logMethod() {

    }

    @Around("logMethod()")
    @SneakyThrows
    public Object handleLog(ProceedingJoinPoint pjp) {
        Object result;
        try {
            putLogInfo2MDC(pjp);
            result = pjp.proceed();
        } finally {
            clearMDC();
        }
        return result;
    }

    private void clearMDC() {
        MDC.remove(JSON_KEY);
    }

    private void putLogInfo2MDC(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Log annotation = signature.getMethod().getAnnotation(Log.class);

        JSONObject json = new JSONObject();
        // 用户
        UserInfo user = UserUtils.getUser();
        if (user != null) {
            json.put("U", user.getId());
        }
        // 操作
        json.put("A", annotation.value());

        MDC.put(JSON_KEY, json.toJSONString());
    }
}
